package demo;

import java.io.File;
import java.net.URISyntaxException;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;

import com.jfinal.core.JFinal;

public class Main {
	final static int port = 8081;
	final static int devPort = 8081;
	final static String devAppDir = "WebRoot";

	public static void main(String[] args) throws Exception {
		String jarFile = getContainingJar();
		if (jarFile != null) {
			runAsProduction(jarFile);
		} else {
			runForDev();
		}
	}

	// 参考 com.jfinal.server.JettyServer.doStart()
	public static void runAsProduction(String jarFile) throws Exception {
		System.out.println("runAsProduction: using webapp from war file: " + jarFile);
		Server server = new Server();
		SelectChannelConnector connector = new SelectChannelConnector();
		connector.setPort(port);
		server.addConnector(connector);
		WebAppContext webApp = new WebAppContext();
		webApp.setThrowUnavailableOnStartupException(true);	// 在启动过程中允许抛出异常终止启动并退出 JVM
		webApp.setContextPath("/");
		webApp.setWar(jarFile);
		webApp.setExtractWAR(false);
		webApp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
		webApp.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
		// webApp.setInitParams(Collections.singletonMap("org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"));
		server.setHandler(webApp);
		System.out.println("Starting web server on port: " + port);
		server.start();
		System.out.println("Starting Complete.");
		server.join();
	}
	
	private static void runForDev() {
		System.out.println("runForDev: using webapp from dir: " + devAppDir);
		// eclipse 下的启动方式
    	JFinal.start(devAppDir, devPort, "/", 5);
    	// IDEA 下的启动方式
    	// JFinal.start("src/main/webapp", 80, "/");
	}
	
	private static String getContainingJar() {
		try {
			File loc = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
			if (loc.isFile()) return loc.getAbsolutePath();
			else {
				System.out.println("getContainingJar: not a jar file: " + loc.getAbsolutePath());
				return null;
			}
		} catch (URISyntaxException e) {
			System.err.println("getContainingJar: can't locate containing jar: " + e.toString());
			return null;
		}
	}
}
